// 导入 http 模块
import http from 'wechat-http'
// 基础路径，同时需添加合法请求域名
http.baseURL = 'https://live-api.itheima.net'

// 1.请求拦截器
http.intercept.request = (config) => {
  // 设置请求头，添加 token
  // console.log(config);
  // 常见错误：config 中没有 header 属性
  // 修改：config.header = {}
  config.header ={
    // 携带token信息
    Authorization: 'Bearer ' +  wx.getStorageSync('token'),
    // 如果传递有header信息，就覆盖添加的header信息
    ...config.header,
  }
  return config
}


// 2.响应拦截器，返回核心数据 data
http.intercept.response = async (res) => {
  if(res.data.code === 10000){
    return res.data
  }else if(res.data.code === 401) {
    const app = getApp()
    if (res.config.url.includes('/refreshToken')) {
      app.setToken('token', '')
      app.setToken('refreshtoken', '')
      const pages = getCurrentPages()
      const page = pages[pages.length - 1]
      wx.redirectTo({
        url: '/pages/login/index?redirectUrl=/' + page.route,
      })
      return 
    }
    const res2 = await http.post(
      '/refreshToken',
      {},
      {
        header: {
          Authorization: `Bearer ` + wx.getStorageSync('refreshToken')
        }
      }
    )
    app.setToken('token', res2.data.token)
    app.setToken('refreshToken', res2.data.refreshToken)
    res.config.header = {
      Authorization: `Bearer ` + wx.getStorageSync('token')
    }
    return http(res.config)
  }
  
  else {
    wx.utils.toast(res.data.message || '请求失败')
    return Promise.reject(res.data)
  }
}

// 普通的模块导出
export default http